Modify a dictionary
A dictionary is a built-in data type that stores data in key-value pairs. Here are some ways to modify a dictionary:
1. Adding a new key-value pair
You can add a new entry to a dictionary by assigning a value to a new key.
Adding new value in dictionary in python
# Create a dictionary
my_dict = {"Python": 1, "Java": 2}
print(f"Original Dictionary: {my_dict}")
# Add a new key-value pair
my_dict["PHP"] = 3
print(f"Dictionary After Adding a New Pair: {my_dict}")
Output
Original Dictionary: {'Python': 1, 'Java': 2}
Dictionary After Adding a New Pair: {'Python': 1, 'Java': 2, 'PHP': 3}
2. Updating an existing key-value pair
If you assign a value to an existing key, it will update the value for that key.
Update dictionary items value in python
# Create a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
print(f"Original Dictionary: {my_dict}")
# Update an existing key-value pair
my_dict["banana"] = 20
print(f"Dictionary After Updating a Pair: {my_dict}")
Output
Original Dictionary: {'apple': 1, 'banana': 2, 'cherry': 3}
Dictionary After Updating a Pair: {'apple': 1, 'banana': 20, 'cherry': 3}
3. Using the update() method
This method can add multiple key-value pairs to the dictionary. It takes another dictionary as its argument.
Updating dictionaries item using update() method
# Create a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
print(f"Original Dictionary: {my_dict}")
# Add multiple key-value pairs
my_dict.update({"dragonfruit": 4, "elderberry": 5})
print(f"Dictionary After Adding Multiple Pairs: {my_dict}")
Output
Original Dictionary: {'apple': 1, 'banana': 2, 'cherry': 3}
Dictionary After Adding Multiple Pairs: {'apple': 1, 'banana': 2, 'cherry': 3, 'dragonfruit': 4, 'elderberry': 5}
4. setdefault() Method
The setdefault(key, default) method retrieves a value for a given key. If the key doesn't exist, it inserts a key-value pair with the provided default value.
Add elements in dictionary using setdefault() method
my_dict = {"first" : "Python", "second": "Java", "third": "PHP"}
default_value = "JavaScript"
second = my_dict.setdefault("second", default_value) # Checks for "name", adds it with default_value if not found
print(second)
print(my_dict)
# If "name" already existed, it would return the existing value
Output
Java
{'first': 'Python', 'second': 'Java', 'third': 'PHP'}
This method is helpful when you want to ensure a key exists and provide a default value if it's missing.
Remember, dictionaries in Python are mutable, which means you can change their content without changing their identity.